#include "parkingrecord.h"
#include "ui_parkingrecord.h"
#include <QTableWidget>
#include <QJsonArray>
#include <QHeaderView>
#include <QPushButton>
#include <QHBoxLayout>
#include <QFileDialog>
#include <QMessageBox>
#include "protocol.h"
#include "tools.h"
ParkingRecord::ParkingRecord(QWidget *parent, QTcpSocket *externalSocket) :
    QWidget(parent),
    ui(new Ui::ParkingRecord),
    socket(externalSocket)
{
    ui->setupUi(this);

    tableWidget = new QTableWidget(this);
    refreshButton = new QPushButton("刷新", this);
    exportButton = new QPushButton("导出", this);

    // 表格列数与表头
    tableWidget->setColumnCount(6);
    tableWidget->setHorizontalHeaderLabels(QStringList() << "车牌号" << "入场时间" << "离场时间" << "费用" << "车位" << "状态");

    // 表格设置自适应列宽
    tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    // 表格设置最小大小
    tableWidget->setMinimumSize(600, 400);

    // 创建按钮的水平布局
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->addWidget(refreshButton);
    buttonLayout->addWidget(exportButton);
    buttonLayout->addStretch();  // 挤到左边，右边留空白

    // 创建整体垂直布局
    mainLayout = new QVBoxLayout(this);
    mainLayout->addLayout(buttonLayout);
    mainLayout->addWidget(tableWidget);

    // 设置窗口使用这个layout
    this->setLayout(mainLayout);
    connect(refreshButton, &QPushButton::clicked, this, &ParkingRecord::onRefreshClicked);
    connect(exportButton, &QPushButton::clicked, this, &ParkingRecord::onExportClicked);

}

ParkingRecord::~ParkingRecord()
{
    delete ui;
}

void ParkingRecord::onRefreshClicked()
{
    //QJsonObject root;
    //QJsonObject message;
    //root["func"] = 9;
    //root["message"] = message;
    //QByteArray dataToSend = Encode(root);
    //socket->write(dataToSend);
    int incompleteRows = countIncompleteLines("parking_record.txt");
    int lines = countLinesInFile("parking_record.txt")-1;
    //qDebug() << "不完整行数为:" << incompleteRows;
    //qDebug() << "总行数:" << lines;
    int n = lines-incompleteRows;
    QJsonObject root;
    QJsonObject message1;
    QJsonObject message2;
    root["func"] = 9;
    //message["signal"] = 1;
    message2["message2"] = message1;
    message2["n"] = n;
    message2["total"]= lines;
    root["message"] = message2;

    QByteArray dataToSend = Encode(root);
    socket->write(dataToSend);
}

void ParkingRecord::onExportClicked()
{
    QString fileName = QFileDialog::getSaveFileName(this, "保存文件", "停车记录表.csv", "CSV文件 (*.csv)");
      if (fileName.isEmpty()) {
          return;  // 用户取消保存
      }

      QFile file(fileName);
      if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
          qDebug() << "无法打开文件:" << file.errorString();
          return;
      }

      QTextStream out(&file);

      // 写表头
      QStringList headers;
      for (int col = 0; col < tableWidget->columnCount(); ++col) {
          headers << tableWidget->horizontalHeaderItem(col)->text();
      }
      out << headers.join(",") << "\n";

      // 写表格数据
      for (int row = 0; row < tableWidget->rowCount(); ++row) {
          QStringList rowData;
          for (int col = 0; col < tableWidget->columnCount(); ++col) {
              QTableWidgetItem *item = tableWidget->item(row, col);
              if (item) {
                  rowData << item->text();
              } else {
                  rowData << "";  // 如果空，写空字符串
              }
          }
          out << rowData.join(",") << "\n";
      }

      file.close();
      qDebug() << "导出成功:" << fileName;
}

void ParkingRecord::loadRecordsFromFile()
{
    QFile file("parking_record.txt");
       if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
           qWarning() << "无法打开文件: parking_record.txt";
           return;
       }

       QTextStream in(&file);
       in.setCodec("UTF-8");

       QVector<QStringList> dataRows;
       bool isFirstLine = true;

       while (!in.atEnd()) {
           QString line = in.readLine().trimmed();
           if (line.isEmpty())
               continue;

           if (isFirstLine) {
               // 跳过表头行
               isFirstLine = false;
               continue;
           }

           // 按tab分割字段
           QStringList fields = line.split('\t', Qt::SkipEmptyParts);
           dataRows.append(fields);
       }

       file.close();

       // 设置表头（写死）
       QStringList headers = {"车牌号", "入场时间", "离场时间", "费用", "车位", "状态"};
       tableWidget->clear();
       tableWidget->setColumnCount(headers.size());
       tableWidget->setHorizontalHeaderLabels(headers);
       tableWidget->setRowCount(dataRows.size());

       // 填充数据
       for (int row = 0; row < dataRows.size(); ++row) {
           const QStringList &fields = dataRows[row];
           for (int col = 0; col < fields.size() && col < headers.size(); ++col) {
               QString cleanField = fields[col].trimmed();
               tableWidget->setItem(row, col, new QTableWidgetItem(cleanField));
           }
       }

       tableWidget->resizeColumnsToContents(); // 可选：自适应列宽
}

//老版本，未进行优化数据获取机制
/*
void ParkingRecord::handleServerMessage(const QJsonObject &jsonObject)
{
    qDebug()<<"ParkingRecord::handleServerMessage:"<<jsonObject;    
    //tableWidget = new QTableWidget(this);

    tableWidget->setColumnCount(6);
    tableWidget->setHorizontalHeaderLabels(QStringList() << "车牌号" << "入场时间" << "离场时间" << "费用" << "车位" << "状态");

    QJsonArray messages = jsonObject["messageArray"].toArray();

    qDebug()<<"QJsonArray messages:"<<messages;
    tableWidget->setRowCount(messages.size());

    for (int i = 0; i < messages.size(); ++i) {
        QJsonObject obj = messages[i].toObject();
        qDebug()<<"obj:"<<obj;
        QString plate = obj["plate"].toString();
        QString entry_time = obj["entry_time"].toString();
        QString exit_time = obj["exit_time"].isNull() ? "-" : obj["exit_time"].toString();
        QString fee = obj["fee"].isNull() ? "-" : obj["fee"].toString();
        QString location = obj["location"].toString();
        QString status = obj["status"].toString();

        tableWidget->setItem(i, 0, new QTableWidgetItem(QString::fromUtf8(plate.toUtf8())));
        tableWidget->setItem(i, 1, new QTableWidgetItem(entry_time));
        tableWidget->setItem(i, 2, new QTableWidgetItem(exit_time));
        tableWidget->setItem(i, 3, new QTableWidgetItem(fee));
        tableWidget->setItem(i, 4, new QTableWidgetItem(location));
        tableWidget->setItem(i, 5, new QTableWidgetItem(status));
    }

    // 可选：自适应列宽
    //tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    tableWidget->show();
    //exportTableToTxt();

}
*/


void ParkingRecord::handleServerMessage(const QJsonObject &jsonObject)
{
    qDebug()<<"ParkingRecord::handleServerMessage:"<<jsonObject;
    int isChanged = jsonObject["isChanged"].toInt();
    qDebug()<<"isChanged:"<<isChanged;
    loadRecordsFromFile();
    if(!isChanged)
    {
        qDebug()<<"no new data,load from local";

        return;
    }
    qDebug()<<"append new data from server";
    QJsonArray messageArray = jsonObject["messageArray"].toArray();
    QJsonArray recordIdsArray = jsonObject["recordIdsArray"].toArray();
    QJsonArray newDataArray = jsonObject["newResult"].toArray();
    qDebug()<<"messageArray"<<messageArray;
    qDebug()<<"recordIdsArray"<<recordIdsArray;
    qDebug()<<"newDataArray"<<newDataArray;

    if(!messageArray.isEmpty()&&!recordIdsArray.isEmpty())
    {
        for (int i = 0; i < recordIdsArray.size(); ++i) {
            int row = recordIdsArray[i].toInt()-1;
            if (row >= tableWidget->rowCount()) {
                qWarning() << "无效的行号:" << row;
                continue;
            }

            QJsonObject obj = messageArray[i].toObject();

            QString plate = obj["plate"].toString();
            QString entry_time = obj["entry_time"].toString();
            QString exit_time = obj.contains("exit_time") && !obj["exit_time"].isNull() ? obj["exit_time"].toString() : "-";
            QString fee = obj.contains("fee") && !obj["fee"].isNull() ? obj["fee"].toString() : "-";
            QString location = obj["location"].toString();
            QString status = obj["status"].toString();

            tableWidget->setItem(row, 0, new QTableWidgetItem(plate));
            tableWidget->setItem(row, 1, new QTableWidgetItem(entry_time));
            tableWidget->setItem(row, 2, new QTableWidgetItem(exit_time));
            tableWidget->setItem(row, 3, new QTableWidgetItem(fee));
            tableWidget->setItem(row, 4, new QTableWidgetItem(location));
            tableWidget->setItem(row, 5, new QTableWidgetItem(status));
        }
    }
    if(!newDataArray.isEmpty())
    {
        for (const QJsonValue &value : newDataArray) {
            QJsonObject obj = value.toObject();

            QString plate = obj["plate"].toString();
            QString entry_time = obj["entry_time"].toString();
            QString exit_time = obj.contains("exit_time") && !obj["exit_time"].isNull() ? obj["exit_time"].toString() : "-";
            QString fee = obj.contains("fee") && !obj["fee"].isNull() ? obj["fee"].toString() : "-";
            QString location = obj["location"].toString();
            QString status = obj["status"].toString();

            int currentRow = tableWidget->rowCount();  // 当前总行数
            tableWidget->insertRow(currentRow);        // 插入新行

            tableWidget->setItem(currentRow, 0, new QTableWidgetItem(plate));
            tableWidget->setItem(currentRow, 1, new QTableWidgetItem(entry_time));
            tableWidget->setItem(currentRow, 2, new QTableWidgetItem(exit_time));
            tableWidget->setItem(currentRow, 3, new QTableWidgetItem(fee));
            tableWidget->setItem(currentRow, 4, new QTableWidgetItem(location));
            tableWidget->setItem(currentRow, 5, new QTableWidgetItem(status));
            }

}

    tableWidget->resizeColumnsToContents();
    tableWidget->show();
    exportTableToTxt();
}

void ParkingRecord::exportTableToTxt()
{
    QString filePath = "parking_record.txt";  // 固定文件名
    QFile file(filePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::warning(this, "导出失败", "无法打开 parking_record.txt 进行写入");
        return;
    }

    QTextStream out(&file);
    out.setCodec("UTF-8");

    // 写入表头
    QStringList headers;
    for (int col = 0; col < tableWidget->columnCount(); ++col) {
        QTableWidgetItem *headerItem = tableWidget->horizontalHeaderItem(col);
        headers << (headerItem ? headerItem->text() : "");
    }
    out << headers.join("\t\t\t") << "\n";

    // 写入每一行数据
    for (int row = 0; row < tableWidget->rowCount(); ++row) {
        QStringList rowData;
        for (int col = 0; col < tableWidget->columnCount(); ++col) {
            QTableWidgetItem *item = tableWidget->item(row, col);
            rowData << (item ? item->text() : "");
        }
        out << rowData.join("\t\t") << "\n";
    }

    file.close();

}

